﻿using WCS.Infrastructure.Attr;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WCS.Infrastructure.IOC
{

    public static class InjectHelper
    {

        /// <summary>
        /// 批量注入方法
        /// </summary>
        /// <param name="services"></param>
        /// <param name="providerAssembly"></param>
        /// <param name="injectAssembly"></param>
        public static void AddScoped(this IServiceCollection services, Assembly providerAssembly, Assembly injectAssembly)
        {
            var providers = providerAssembly.GetTypes().Where(d => d.GetCustomAttribute(typeof(ProviderAttribute)) != null).ToList();
            var injects = injectAssembly.GetTypes().Where(d => d.GetCustomAttribute(typeof(InjectAttribute)) != null).ToList();

            foreach (var item in providers)
            {
                var children = injects.Where(d => item.IsAssignableFrom(d)).ToList();
                foreach (var child in children)
                {
                    services.AddScoped(item, child);
                }
            }
        }

        public static void AddTransient(this IServiceCollection services, Assembly providerAssembly, Assembly injectAssembly)
        {
            var providers = providerAssembly.GetTypes().Where(d => d.GetCustomAttribute(typeof(ProviderAttribute)) != null).ToList();
            var injects = injectAssembly.GetTypes().Where(d => d.GetCustomAttribute(typeof(InjectAttribute)) != null).ToList();

            foreach (var item in providers)
            {
                var children = injects.Where(d => item.IsAssignableFrom(d)).ToList();
                foreach (var child in children)
                {
                    services.AddTransient(item, child);
                }
            }
        }

        public static void AddSingleton(this IServiceCollection services, Assembly providerAssembly, Assembly injectAssembly)
        {
            var providers = providerAssembly.GetTypes().Where(d => d.GetCustomAttribute(typeof(ProviderAttribute)) != null).ToList();
            var injects = injectAssembly.GetTypes().Where(d => d.GetCustomAttribute(typeof(InjectAttribute)) != null).ToList();

            foreach (var item in providers)
            {
                var children = injects.Where(d => item.IsAssignableFrom(d)).ToList();
                foreach (var child in children)
                {
                    services.AddSingleton(item, child);
                }
            }
        }

    }
}
